package com.projet.glb2r.Base_et_Provider;



import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;

public class Provider extends ContentProvider{
	String TAG = "Provider";

	public static String AUTHORITY = "com.projet.glb2r.Base_et_Provider";

	public static final Uri CONTENT_URI_CLIENT = Uri.parse("content://" + AUTHORITY + "/tableclient");
	public static final Uri CONTENT_URI_ENTREPRISE = Uri.parse("content://" + AUTHORITY + "/table_entreprise");
	public static final Uri CONTENT_URI_PRODUIT = Uri.parse("content://" + AUTHORITY + "/tableproduit");
	public static final Uri CONTENT_URI_FACTURE = Uri.parse("content://" + AUTHORITY + "/tablefacture");
	public static final Uri CONTENT_URI_PRODUITSFACTURES = Uri.parse("content://" + AUTHORITY + "/tableproduitsfactures");
	public static final Uri CONTENT_URI_ASSOCEFACTUREPRODUITS = Uri.parse("content://" + AUTHORITY + "/tableassocefacturesproduits");

	// MIME types used for searching words or looking up a single definition
	public static final String NOM_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE +
			"/vnd.projet.glb2r.Base_et_Provider.ActiviteRechercheClient";
	public static final String DEFINITION_MIME_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE +
			"/vnd.projet.glb2r.Base_et_Provider.ActiviteRechercheCLient";

	private TableClient tableClient;
	private TableEntreprise tableEntreprise;
	private TableProduit tableProduit;
	private TableFacture tableFacture; 
	private TableProduitsFactures tableProduitFacture;
	private TableAssoceFactProduit tableAssoceFactProduit;


	// UriMatcher stuff
	private static final int SEARCH_NOM = 0;
	private static final int GET_NOM = 1;
	private static final int SEARCH_SUGGEST = 2;
	private static final int REFRESH_SHORTCUT = 3;
	private static final int ENTREPRISE = 4;
	private static final int PRODUIT = 5;
	private static final int FACTURE = 6;
	private static final int PRODUITFACTURE = 7;
	private static final int SEARCH_PRODUIT = 8;
	private static final int ASSOCEFACTURESPRODUITS = 9;
	private static final int SEARCH_SUGGESTPRODUIT = 10;
	private static final int SEARCH_SUGGESTFACTURE = 11;
	private static final int SEARCH_FACTURE = 12;
	private static final int GET_PRODUIT = 13;	
	private static final int GET_FACTURE = 14;
			
	public static final UriMatcher sURIMatcher = buildUriMatcher();


	/**
	 * Builds up a UriMatcher for search suggestion and shortcut refresh queries.
	 */
	private static UriMatcher buildUriMatcher() {
		UriMatcher matcher =  new UriMatcher(UriMatcher.NO_MATCH);
		// to get definitions...
		matcher.addURI(AUTHORITY, "tableclient", SEARCH_NOM);
		matcher.addURI(AUTHORITY, "tableclient/#", GET_NOM);

		matcher.addURI(AUTHORITY,"table_entreprise" ,ENTREPRISE);
		matcher.addURI(AUTHORITY,"tableproduit" , PRODUIT);
		
		//matcher.addURI(AUTHORITY, "tableproduits", SEARCH_PRODUIT);
		//matcher.addURI(AUTHORITY, "tableproduit/#",GET_PRODUIT);

		matcher.addURI(AUTHORITY,"tablefacture" , FACTURE);
		matcher.addURI(AUTHORITY,"tablefacture/#" , GET_FACTURE);
		matcher.addURI(AUTHORITY,"tableproduitsfactures" , PRODUITFACTURE);
		
		matcher.addURI(AUTHORITY, "tableassocefacturesproduits", ASSOCEFACTURESPRODUITS);

		// to get suggestions...
		matcher.addURI(AUTHORITY ,"rechercheClient/" + SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGEST);		
		matcher.addURI(AUTHORITY, "rechercheProduit/" + SearchManager.SUGGEST_URI_PATH_QUERY  , SEARCH_SUGGESTPRODUIT);
		matcher.addURI(AUTHORITY, "rechercheFacture/" + SearchManager.SUGGEST_URI_PATH_QUERY  , SEARCH_SUGGESTFACTURE);
		
		/* The following are unused in this implementation, but if we include
		 * {@link SearchManager#SUGGEST_COLUMN_SHORTCUT_ID} as a column in our suggestions table, we
		 * could expect to receive refresh queries when a shortcutted suggestion is displayed in
		 * Quick Search Box, in which case, the following Uris would be provided and we
		 * would return a cursor with a single item representing the refreshed suggestion data.
		 */
		matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT, REFRESH_SHORTCUT);
		matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*", REFRESH_SHORTCUT);

		return matcher;
	}


	@Override
	public boolean onCreate() {
		tableClient = new TableClient(getContext());
		tableEntreprise = new TableEntreprise(getContext());
		tableProduit = new TableProduit(getContext());
		tableFacture = new TableFacture(getContext());
		tableProduitFacture = new TableProduitsFactures(getContext());
		tableAssoceFactProduit = new TableAssoceFactProduit(getContext());
		return true;
	}

	/**
	 * Handles all the dictionary searches and suggestion queries from the Search Manager.
	 * When requesting a specific word, the uri alone is required.
	 * When searching all of the dictionary for matches, the selectionArgs argument must carry
	 * the search query as the first element.
	 * All other arguments are ignored.
	 */

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
			String sortOrder) {

		//SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
		// Use the UriMatcher to see what kind of query we have and format the db query accordingly
		switch (sURIMatcher.match(uri)) {
		
		case SEARCH_SUGGEST:
			if (selectionArgs == null) {
				throw new IllegalArgumentException(
						"selectionArgs must be provided for the Uri: " + uri);
			}
			return getSuggestions(selectionArgs[0]);
		
		
		case SEARCH_SUGGESTPRODUIT:
			
			
			if (selectionArgs == null) {
				throw new IllegalArgumentException(
						"selectionArgs must be provided for the Uri: " + uri);
			}
			
			return getProduitSuggestions(selectionArgs[0]);
		
		case SEARCH_SUGGESTFACTURE:
			
			
			if (selectionArgs == null) {
				throw new IllegalArgumentException(
						"selectionArgs must be provided for the Uri: " + uri);
			}
			
			return getFactureSuggestions(selectionArgs[0]);
	
		case SEARCH_NOM:
			if (selection== null){
				if (selectionArgs == null) {
					throw new IllegalArgumentException(
							"selectionArgs must be provided for the Uri: " + uri);
				}
				return search(selectionArgs[0]);
			}
			else
				return getClient(projection, selection, selectionArgs);
		
		case SEARCH_PRODUIT:
			if (selectionArgs == null) {
				throw new IllegalArgumentException(
						"selectionArgs must be provided for the Uri: " + uri);
			}
			return searchProduit(selectionArgs[0]);
			
	
		case SEARCH_FACTURE:
			if (selectionArgs == null) {
				throw new IllegalArgumentException(
						"selectionArgs must be provided for the Uri: " + uri);
			}
			return searchFacture(selectionArgs[0]);

		case GET_NOM:
			return getClient(uri);
			
		case GET_PRODUIT:
			return getProduitURI(uri);
			
		case GET_FACTURE:
			return getFacture(uri);
			
		case REFRESH_SHORTCUT:
			return refreshShortcut(uri);
			
		case ENTREPRISE :
			return getEntreprise(projection, selection, selectionArgs);
			
		case PRODUIT:
			if (selection== null){
				if (selectionArgs == null) {
					throw new IllegalArgumentException(
							"selectionArgs must be provided for the Uri: " + uri);
				}
				return searchProduit(selectionArgs[0]);
			}
			else
				return getProduit(projection, selection, selectionArgs);
			
		case FACTURE :
			return getFacture(projection, selection, selectionArgs);
		
		case PRODUITFACTURE:
				return getProduitFacture(projection, selection, selectionArgs);
				
		case ASSOCEFACTURESPRODUITS:
			return getAssoceFactProd(projection, selection, selectionArgs);
			
		default:
			throw new IllegalArgumentException("Unknown Uri: " + uri);
		}
		//	        SQLiteDatabase db = baseClient.getWritableDatabase();
		//            Cursor cursor = queryBuilder.query(db, projection, selection,
		//            		selectionArgs, null, null, sortOrder);
		//            // Make sure that potential listeners are getting notified
		//            cursor.setNotificationUri(getContext().getContentResolver(), uri);
	}

	private Cursor getAssoceFactProd(String[] projection, String selection,	String[] selectionArgs) {
		return tableAssoceFactProduit.getAssoceFactProd(projection, selection, selectionArgs);
	}


	private Cursor getFacture(String[] projection, String selection,String[] selectionArgs) {
		return tableFacture.getFacture(projection, selection, selectionArgs);
	}
	
	private Cursor getClient(String[] projection, String selection,String[] selectionArgs) {
		return tableClient.getClient(projection, selection, selectionArgs);
	}


	private Cursor getEntreprise(String[] projection, String selection,String[] selectionArgs) {
		return tableEntreprise.getEntreprise(projection, selection, selectionArgs);
	}


	private Cursor getProduitFacture(String[] columns, String selection, String[] selectionArgs) {
		return tableProduitFacture.getProduitsFactures(columns, selection, selectionArgs);
	}


	private Cursor getProduit(String [] columns, String selection, String[] selectionArgs) {
		return tableProduit.getAllProduit(columns,selection,selectionArgs);
	}



	private Cursor getSuggestions(String query) {
		query = query.toLowerCase();
		String[] columns = new String[] {
				BaseColumns._ID,
				TableClient.KEY_NOMCLIENT,
				TableClient.KEY_PRENOMCLIENT,
				
				SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID};

		return tableClient.getClientMatches(query, columns);
	}
	
	private Cursor getProduitSuggestions(String query) {
		query = query.toLowerCase();
		String[] columns = new String[] {
				TableProduit.KEY_ROWID,
				TableProduit.KEY_NOM,
				
				SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID};

		return tableProduit.getProduitMatches(query, columns);
	}
	
	private Cursor getFactureSuggestions(String query) {
		query = query.toLowerCase();
		String[] columns = new String[] {
				BaseColumns._ID,
				TableFacture.KEY_DATE,
				
				
				SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID};

		return tableFacture.getFactureMatches(query, columns);
	}


	private Cursor search(String query) {
		query = query.toLowerCase();
		String[] columns = new String[] {
				BaseColumns._ID,
				TableClient.KEY_NOMCLIENT,
				TableClient.KEY_PRENOMCLIENT
		};

		return tableClient.getClientMatches(query, columns);
	}
	
	private Cursor searchProduit(String query) {
		query = query.toLowerCase();
		String[] columns = new String[] {
				BaseColumns._ID,
				TableProduit.KEY_NOM,
		};

		return tableProduit.getProduitMatches(query, columns);
	}
	
	private Cursor searchFacture(String query) {
		query = query.toLowerCase();
		String[] columns = new String[] {
				BaseColumns._ID,
				TableFacture.KEY_DATE,
				//TableFacture.KEY_ROWID
		};

		return tableFacture.getFactureMatches(query, columns);
	}



	//getproduitavec URI
	
	private Cursor getProduitURI(Uri uri) {
		String rowId = uri.getLastPathSegment();
		String[] columns = new String[] {
				TableProduit.KEY_NOM,
				TableProduit.KEY_ROWID};

		return tableProduit.getProduit(rowId, columns);
	
	}

	
	private Cursor getClient(Uri uri) {
		String rowId = uri.getLastPathSegment();
		String[] columns = new String[] {
				TableClient.KEY_NOMCLIENT,
				TableClient.KEY_PRENOMCLIENT,
				BaseColumns._ID
		};

		return tableClient.getClient(rowId, columns);
	}
	
	
	private Cursor getFacture(Uri uri) {
		String rowId = uri.getLastPathSegment();
		String[] columns = new String[] {
				TableFacture.KEY_DATE,
				//TableFacture.KEY_ROWID
				BaseColumns._ID
		};

		return tableFacture.getFacture(rowId, columns);
	}


	private Cursor refreshShortcut(Uri uri) {
		/* This won't be called with the current implementation, but if we include
		 * {@link SearchManager#SUGGEST_COLUMN_SHORTCUT_ID} as a column in our suggestions table, we
		 * could expect to receive refresh queries when a shortcutted suggestion is displayed in
		 * Quick Search Box. In which case, this method will query the table for the specific
		 * word, using the given item Uri and provide all the columns originally provided with the
		 * suggestion query.
		 */
		Cursor result;
		String rowId = uri.getLastPathSegment();
		if(uri.equals(CONTENT_URI_CLIENT)){
		String[] columns = new String[] {
				BaseColumns._ID,
				TableClient.KEY_NOMCLIENT,
				TableClient.KEY_PRENOMCLIENT,
				SearchManager.SUGGEST_COLUMN_SHORTCUT_ID,
				SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID};

		result= tableClient.getClient(rowId, columns);
		}
		else{
			String[] columns = new String[] {
					BaseColumns._ID,
					TableFacture.KEY_DATE,
					//TableProduit.KEY_PRIX,
					SearchManager.SUGGEST_COLUMN_SHORTCUT_ID,
					SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID};

			result= tableFacture.getFacture(rowId, columns);
		}
		return result;
	}

	/**
	 * This method is required in order to query the supported types.
	 * It's also useful in our own query() method to determine the type of Uri received.
	 */
	@Override
	public String getType(Uri uri) {
		switch (sURIMatcher.match(uri)) {
		case SEARCH_NOM:
			return NOM_MIME_TYPE;
		case GET_NOM:
			return DEFINITION_MIME_TYPE;
		case SEARCH_SUGGEST:
			return SearchManager.SUGGEST_MIME_TYPE;
		case REFRESH_SHORTCUT:
			return SearchManager.SHORTCUT_MIME_TYPE;
		default:
			throw new IllegalArgumentException("Unknown URL " + uri);
		}
	}
 
	// Other required implementations...

	@Override
	public Uri insert(Uri uri, ContentValues values) {		 
		switch (sURIMatcher.match(uri)) {


		case SEARCH_NOM:
			long rowId = tableClient.insert(values);
			Uri inuri1 = null;
			if (rowId>0){
				inuri1 = ContentUris.withAppendedId(CONTENT_URI_CLIENT, rowId);
				getContext().getContentResolver().notifyChange(uri, null);

			}
			return inuri1;
			//throw new UnsupportedOperationException("Failed to insert row into"+uri);

		case ENTREPRISE:
			long rowId2 = tableEntreprise.insert(values);
			Uri inuri2 = null;
			if (rowId2>0){
				inuri2 = ContentUris.withAppendedId(CONTENT_URI_ENTREPRISE, rowId2);
				getContext().getContentResolver().notifyChange(inuri2, null);
			}
			//throw new UnsupportedOperationException("Failed to insert row into"+uri);
			return inuri2;

		case PRODUIT:
			long rowId3 = tableProduit.insert(values);
			Uri inuri3 = null;
			if (rowId3>0){
				inuri3 = ContentUris.withAppendedId(CONTENT_URI_PRODUIT, rowId3);
				getContext().getContentResolver().notifyChange(inuri3, null);

			}
			
			//throw new UnsupportedOperationException("Failed to insert row into"+uri);
			return inuri3;

		case FACTURE:
			long rowId4 = tableFacture.insert(values);
			Uri inuri4 = null;
			if (rowId4>0){
				inuri4 = ContentUris.withAppendedId(CONTENT_URI_FACTURE, rowId4);
				getContext().getContentResolver().notifyChange(uri, null);

			}
			return inuri4; 
			
		case PRODUITFACTURE:
			long rowId5 = tableProduitFacture.insert(values);
			Uri inuri5 = null;
			if (rowId5>0){
				inuri5 = ContentUris.withAppendedId(CONTENT_URI_PRODUITSFACTURES, rowId5);
				getContext().getContentResolver().notifyChange(inuri5, null);

			}
			return inuri5;
			
		case ASSOCEFACTURESPRODUITS:
			long rowId6 = tableAssoceFactProduit.insert(values);
			Uri inuri6 = null;
			if (rowId6>0){
				inuri6 = ContentUris.withAppendedId(CONTENT_URI_ASSOCEFACTUREPRODUITS, rowId6);
				getContext().getContentResolver().notifyChange(inuri6, null);

			}
			return inuri6;
			
			//throw new UnsupportedOperationException("Failed to insert row into"+uri);
			

		default:
			throw new IllegalArgumentException("Unknown Uri: " + uri);


		}
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {

		switch(sURIMatcher.match(uri)){

		case SEARCH_NOM:
			return deleteClient(CONTENT_URI_CLIENT, selection, selectionArgs);

		case ENTREPRISE:
			return deleteEntreprise(CONTENT_URI_ENTREPRISE, selection, selectionArgs);	

		case PRODUIT :
			return deleteProduit(CONTENT_URI_PRODUIT, selection, selectionArgs);
		}
		return 0;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		long id = getId(uri);

		try {
			if (id < 0)
				return tableClient.update(values, selection, selectionArgs);
			else
				return tableClient.update(values, TableClient.KEY_ROWID + "=" + id, null);
		} finally {
			tableClient.close();
		}
	}


	private int deleteClient(Uri uri, String selection, String[] selectionArgs) {
		long id = getId(uri);
		try {
			if (id < 0)
				return tableClient.delete(selection, selectionArgs);
			else
				return tableClient.delete(TableClient.KEY_ROWID + "=" + id, selectionArgs);
				//return baseClient.delete(BaseColumns._ID + "=" + id, selectionArgs);
		} finally {
			tableClient.close();
		}
	}

	private int deleteEntreprise(Uri uri, String selection, String[] selectionArgs) {
		long id = getId(uri);
		try {
			if (id < 0)
				return tableEntreprise.delete(selection, selectionArgs);
			else
				return tableEntreprise.delete(TableEntreprise.KEY_ROWID + "=" + id, selectionArgs);
				//return baseEntreprise.delete(BaseColumns._ID + "=" + id, selectionArgs);
			
		} finally {
			tableEntreprise.close();
		}
	}


		private int deleteProduit(Uri uri, String selection, String[] selectionArgs) {
		long id = getId(uri);
		try {
			if (id < 0)
				return tableProduit.delete(selection, selectionArgs);
			else
				return tableProduit.delete(TableProduit.KEY_ROWID + "=" + id, selectionArgs);
		} finally {
			tableProduit.close();
		}
	}
	
	private long getId(Uri uri) {
		String lastPathSegment = uri.getLastPathSegment();
		if (lastPathSegment != null) {
			try {
				return Long.parseLong(lastPathSegment);
			} catch (NumberFormatException e) {
				Log.e("AppliProvider", "Number Format Exception : " + e);
			}
		}
		return -1;
	}


}

